rm(list = ls())

# Models without district FEs

# Libraries
library(lfe)
library(interflex)

# Load data
load(file = 'models1and2.RData')
load(file = 'model3.RData')

# Functions to Create Plots
intEffect <- function(model, X, Z, XZ, N = 10){
  Zvalues <- seq(min(model.frame(model)[Z]), max(model.frame(model)[Z]), length.out = N)
  out <- matrix(NA, nrow = N, ncol = 5)
  colnames(out) <- c('beta', 'se', 'lb', 'ub', 'Zvalues')
  betas <- coef(model)
  vcMatrix <- vcov(model)
  for(i in 1:N){
    out[i,'beta'] <- betas[X] + Zvalues[i] * betas[XZ]
    out[i,'se'] <- sqrt(vcMatrix[X, X] + Zvalues[i]^2 * vcMatrix[XZ, XZ] + 2 * Zvalues[i] * vcMatrix[X, XZ])
    out[i, 'lb'] <- out[i,'beta'] + out[i,'se'] * qt(0.025, df = model$df.residual)
    out[i, 'ub'] <- out[i,'beta'] + out[i,'se'] * qt(0.975, df = model$df.residual)
  }
  out[, 'Zvalues'] <- Zvalues
  return(out)
}

# Reverse the coding for diffVS
finalDf$diffVSnew <- 100 - finalDf$diffVS 
finalDfPR$diffVSnew <- 100 - finalDfPR$diffVS 

# New interaction
finalDf$diffSMDPnew <- finalDf$onlySMDP * finalDf$diffVSnew
finalDfPR$diffRanknew <- finalDfPR$scale_rank * finalDfPR$diffVSnew

# Number of observations
nrow(finalDf)
nrow(finalDfPR)

# Number of unique candidates
length(unique(finalDf$id))
length(unique(finalDfPR$id))

################################################
#### Body of the paper results + Appendix C ####
################################################

# Run Models
m1 <- felm(pct_spending ~ diffVSnew + onlySMDP + incumbent + woman | party + electorate + election_year | 0 | id, data = subset(finalDf))
m2 <- felm(pct_spending ~ diffVSnew + onlySMDP + diffSMDPnew + incumbent + woman   | party + electorate + election_year | 0 | id, data = finalDf)
m3 <- felm(pct_spending ~ diffVSnew + scale_rank + diffRanknew  + incumbent + woman  |  party + electorate + election_year | 0 | id, data = finalDfPR)

# Create Table 1
stargazer::stargazer(m1, m2, m3, 
                     order = c('diffVSnew', 'onlySMDP', 'diffSMDPnew', 'scale_rank', 'diffRanknew', 'incumbent', 'woman'),
                     covariate.labels = c('Electoral Competitiveness', 
                                          'Only SMDP',
                                          'Electoral Competitiveness x Only SMDP', 
                                          'List Rank', 
                                          'Electoral Competitiveness x List Rank',
                                          'Incumbent',
                                          'Gender = Woman'
                     ),
                     dep.var.labels = 'Spending (%)',
                     add.lines = list(c('FE by Party', 'Yes', 'Yes', 'Yes'),
                                      c('FE by Election', 'Yes', 'Yes', 'Yes'),
                                      c('FE by District', 'Yes', 'Yes', 'Yes')),
                     no.space = TRUE,
                     single.row = FALSE,
                     star.cutoffs = c(0.1, 0.05, 0.01),
                     omit.stat = c("ser", 'f'),
                     # omit.table.layout = "n",
                     title = "Campaign spending in New Zealand, 2014-2021",
                     label = 't:main')


# Figure 1
H2a <- intEffect(m2, X = "onlySMDP", Z = "diffVSnew", XZ = "diffSMDPnew", N = 100)
par(mar = c(5, 5, 2, 2))
plot(y = H2a[,'beta'], x = H2a[,'Zvalues'], 
     ylim = c(-60, 60),
     xlim = c(20, 100),
     type = 'n', 
     xlab = "Electoral Competitiveness", 
     ylab = "Marginal Effect of Only SMDP",  
     cex = 1.75,
     cex.lab = 1.75,
     axes = FALSE)
polygon(x = c(H2a[,'Zvalues'], rev(H2a[,'Zvalues'])),
        y = c(H2a[,'lb'], rev(H2a[,'ub'])),
        col = adjustcolor("grey", alpha.f = 0.95), 
        border = NA)
lines(x = H2a[,'Zvalues'], y = H2a[,'beta'], lty = 1, col = 'white', lwd = 3)
rug(unlist(model.frame(m2)['diffVSnew']))
axis(1, cex.axis = 1.5, at = seq(25, 100, 12.5))
axis(2, cex.axis = 1.5)
abline(h = 0, lty = 2, lwd = 0.5)

# Figure 2 
H3 <- intEffect(m3, X = "scale_rank", Z = "diffVSnew", XZ = "diffRanknew", N = 100)
par(mar = c(5, 5, 2, 2))
plot(y = H3[,'beta'], x = H3[,'Zvalues'], 
     ylim = c(-25, 65),
     xlim = c(25, 100),
     type = 'n', 
     xlab = "Electoral Competitiveness", 
     ylab = "Marginal Effect of List Rank",  
     cex = 1.75,
     cex.lab = 1.75,
     axes = FALSE)
polygon(x = c(H3[,'Zvalues'], rev(H3[,'Zvalues'])),
        y = c(H3[,'lb'], rev(H3[,'ub'])),
        col = adjustcolor("grey", alpha.f = 0.95), 
        border = NA)
lines(x = H3[,'Zvalues'], y = H3[,'beta'], lty = 1, col = 'white', lwd = 3)
rug(unlist(model.frame(m3)['diffVSnew']))
axis(1, cex.axis = 1.5, at = seq(25, 100, 12.5))
axis(2, cex.axis = 1.5)
abline(h = 0, lty = 2, lwd = 0.5)

# Figure C.2 
H3op <- intEffect(m3, X = "diffVSnew", Z = "scale_rank", XZ = "diffRanknew", N = 100)
par(mar = c(5, 7, 2, 2))
plot(y = H3op[,'beta'], x = H3op[,'Zvalues'], 
     ylim = c(-0.5, 2.5),
     xlim = c(0, 1),
     type = 'n', 
     xlab =  "List Rank",
     ylab =  "Marginal Effect of \n Electoral Competitiveness", 
     cex = 1.75,
     cex.lab = 1.75,
     axes = FALSE
)
polygon(x = c(H3op[,'Zvalues'], rev(H3op[,'Zvalues'])),
        y = c(H3op[,'lb'], rev(H3op[,'ub'])),
        col = adjustcolor("grey", alpha.f = 0.95), 
        border = NA)
lines(x = H3op[,'Zvalues'], y = H3op[,'beta'], lty = 1, col = 'white', lwd = 3)
rug(unlist(model.frame(m3)['scale_rank']))
axis(1, cex.axis = 1.5, at = seq(0, 1, 0.25))
axis(2, cex.axis = 1.5)
abline(h = 0, lty = 2, lwd = 0.5)

######################
##### Appendix A #####
######################

# Data for Table A.1
summary(finalDf[, c("pct_spending", 'spending', 
                    "diffVSnew", "onlySMDP", 
                    "incumbent", "woman")])
summary(finalDfPR[, c("pct_spending", 'spending', 
                      "diffVSnew", "scale_rank", 
                      "incumbent", "woman")])

# Figure A.1 
hist(finalDf$diffVSnew, xlab = 'Electoral Competitiveness', ylim = c(0, 200), main = '')
hist(finalDfPR$diffVSnew, xlab = 'Electoral Competitiveness', ylim = c(0, 200), main = '')

######################
##### Appendix B #####
######################

####### Table B.3: Spending in NZ$ ####### 
# Run Models
m1 <- felm(spending ~ diffVSnew + onlySMDP + incumbent + woman | party + electorate + election_year | 0 | id, data = finalDf)
m2 <- felm(spending ~ diffVSnew + onlySMDP + diffSMDPnew + incumbent + woman   | party + electorate + election_year | 0 | id, data = finalDf)
m3 <- felm(spending ~ diffVSnew + scale_rank + diffRanknew  + incumbent + woman  |  party + electorate + election_year | 0 | id, data = finalDfPR)

# Create Table
stargazer::stargazer(m1, m2, m3, 
                     order = c('diffVSnew', 'onlySMDP', 'diffSMDPnew', 'scale_rank', 'diffRanknew', 'incumbent', 'woman'),
                     covariate.labels = c('Electoral Competitiveness', 
                                          'Only SMDP',
                                          'Electoral Competitiveness x Only SMDP', 
                                          'List Rank', 
                                          'Electoral Competitiveness x List Rank',
                                          'Incumbent',
                                          'Gender = Woman'
                     ),
                     dep.var.labels = 'Spending (%)',
                     add.lines = list(c('FE by Party', 'Yes', 'Yes', 'Yes'),
                                      c('FE by Election', 'Yes', 'Yes', 'Yes'),
                                      c('FE by District', 'Yes', 'Yes', 'Yes')),
                     no.space = TRUE,
                     single.row = FALSE,
                     star.cutoffs = c(0.1, 0.05, 0.01),
                     omit.stat = c("ser", 'f'),
                     # omit.table.layout = "n",
                     title = "Campaign spending in New Zealand, 2014-2021---DV: Spending in NZ$",
                     label = 't:nominalSpending')

####### Table B.4: Spending in %, Logit Transformed ####### 
# Run Models
m1 <- felm(pct_spending_l ~ diffVSnew + onlySMDP + incumbent + woman | party + electorate + election_year | 0 | id, data = finalDf)
m2 <- felm(pct_spending_l ~ diffVSnew + onlySMDP + diffSMDPnew + incumbent + woman   | party + electorate + election_year | 0 | id, data = finalDf)
m3 <- felm(pct_spending_l ~ diffVSnew + scale_rank + diffRanknew  + incumbent + woman  |  party + electorate + election_year | 0 | id, data = finalDfPR)

# Create Table
stargazer::stargazer(m1, m2, m3, 
                     order = c('diffVSnew', 'onlySMDP', 'diffSMDPnew', 'scale_rank', 'diffRanknew', 'incumbent', 'woman'),
                     covariate.labels = c('Electoral Competitiveness', 
                                          'Only SMDP',
                                          'Electoral Competitiveness x Only SMDP', 
                                          'List Rank', 
                                          'Electoral Competitiveness x List Rank',
                                          'Incumbent',
                                          'Gender = Woman'
                     ),
                     dep.var.labels = 'Spending (%)',
                     add.lines = list(c('FE by Party', 'Yes', 'Yes', 'Yes'),
                                      c('FE by Election', 'Yes', 'Yes', 'Yes'),
                                      c('FE by District', 'Yes', 'Yes', 'Yes')),
                     no.space = TRUE,
                     single.row = FALSE,
                     star.cutoffs = c(0.1, 0.05, 0.01),
                     omit.stat = c("ser", 'f'),
                     # omit.table.layout = "n",
                     title = "Campaign spending in New Zealand, 2014-2021---DV: %, Logit Transformed",
                     label = 't:logitTransformed')


####### Table B.5: Spending in Logged Spending ####### 
# Run Models
m1 <- felm(spending_ln ~ diffVSnew + onlySMDP + incumbent + woman | party + electorate + election_year | 0 | id, data = subset(finalDf))
m2 <- felm(spending_ln ~ diffVSnew + onlySMDP + diffSMDPnew + incumbent + woman   | party + electorate + election_year | 0 | id, data = finalDf)
m3 <- felm(spending_ln ~ diffVSnew + scale_rank + diffRanknew  + incumbent + woman  |  party + electorate + election_year | 0 | id, data = finalDfPR)

# Create Table
stargazer::stargazer(m1, m2, m3, 
                     order = c('diffVSnew', 'onlySMDP', 'diffSMDPnew', 'scale_rank', 'diffRanknew', 'incumbent', 'woman'),
                     covariate.labels = c('Electoral Competitiveness', 
                                          'Only SMDP',
                                          'Electoral Competitiveness x Only SMDP', 
                                          'List Rank', 
                                          'Electoral Competitiveness x List Rank',
                                          'Incumbent',
                                          'Gender = Woman'
                     ),
                     dep.var.labels = 'Spending (%)',
                     add.lines = list(c('FE by Party', 'Yes', 'Yes', 'Yes'),
                                      c('FE by Election', 'Yes', 'Yes', 'Yes'),
                                      c('FE by District', 'Yes', 'Yes', 'Yes')),
                     no.space = TRUE,
                     single.row = FALSE,
                     star.cutoffs = c(0.1, 0.05, 0.01),
                     omit.stat = c("ser", 'f'),
                     # omit.table.layout = "n",
                     title = "Campaign spending in New Zealand, 2014-2021---DV: Spending logged NZ$",
                     label = 't:loggedNominal')


######################
##### Appendix D #####
######################

# Run Models
m2 <- interflex(Y = 'pct_spending', D = 'onlySMDP', X = 'diffVSnew',
                base = 0,
                estimator = "kernel", 
                vcov.type = 'cluster', 
                cl = 'id',
                Z =  c('incumbent', 'woman'),
                FE = c('party', 'electorate', 'election_year'),
                data = finalDf)
m3 <- interflex(Y = 'pct_spending', D = 'scale_rank', X = 'diffVSnew',
                estimator = "kernel", 
                vcov.type = 'cluster', 
                cl = 'id',
                Z =  c('incumbent', 'woman'),
                FE = c('party', 'electorate', 'election_year'),
                data = finalDfPR)

# Figure D.3
plot(m2, xlab = 'Electoral Competitiveness'
     , ylab = 'Marginal Effect of SMDP Only'
     , show.grid = FALSE
     , theme.bw = TRUE)
plot(m3, xlab = 'Electoral Competitiveness'
     , ylab = 'Marginal Effect of List Rank'
     , show.grid = FALSE
     , theme.bw = TRUE)


######################
##### Appendix E #####
######################

# Compare sample
t.test(finalDf$incumbent ~ finalDf$onlySMDP)
t.test(finalDf$woman ~ finalDf$onlySMDP)

######################
##### Appendix F #####
######################

# Run Models, 
m1 <- felm(pct_spending ~ diffVSnew + onlySMDP + incumbent + woman | party  + election_year | 0 | id, data = subset(finalDf))
m2 <- felm(pct_spending ~ diffVSnew + onlySMDP + diffSMDPnew + incumbent + woman   | party + election_year | 0 | id, data = finalDf)
m3 <- felm(pct_spending ~ diffVSnew + scale_rank + diffRanknew  + incumbent + woman  |  party  + election_year | 0 | id, data = finalDfPR)

summary(m1)
summary(m2)
summary(m3)

# Create Table F.7
stargazer::stargazer(m1, m2, m3, 
                     order = c('diffVSnew', 'onlySMDP', 'diffSMDPnew', 'scale_rank', 'diffRanknew', 'incumbent', 'woman'),
                     covariate.labels = c('Electoral Competitiveness', 
                                          'Only SMDP',
                                          'Electoral Competitiveness x Only SMDP', 
                                          'List Rank', 
                                          'Electoral Competitiveness x List Rank',
                                          'Incumbent',
                                          'Gender = Woman'
                     ),
                     dep.var.labels = 'Spending (%)',
                     add.lines = list(c('FE by Party', 'Yes', 'Yes', 'Yes'),
                                      c('FE by Election', 'Yes', 'Yes', 'Yes')),
                     no.space = TRUE,
                     single.row = FALSE,
                     star.cutoffs = c(0.1, 0.05, 0.01),
                     omit.stat = c("ser", 'f'),
                     # omit.table.layout = "n",
                     title = "Campaign spending in New Zealand, 2014-2021",
                     label = 't:main')


# Figure F.4
H2a <- intEffect(m2, X = "onlySMDP", Z = "diffVSnew", XZ = "diffSMDPnew", N = 100)
par(mar = c(5, 5, 2, 2))
plot(y = H2a[,'beta'], x = H2a[,'Zvalues'], 
     ylim = c(-60, 60),
     xlim = c(20, 100),
     type = 'n', 
     xlab = "Electoral Competitiveness", 
     ylab = "Marginal Effect of Only SMDP",  
     cex = 1.75,
     cex.lab = 1.75,
     axes = FALSE)
polygon(x = c(H2a[,'Zvalues'], rev(H2a[,'Zvalues'])),
        y = c(H2a[,'lb'], rev(H2a[,'ub'])),
        col = adjustcolor("grey", alpha.f = 0.95), 
        border = NA)
lines(x = H2a[,'Zvalues'], y = H2a[,'beta'], lty = 1, col = 'white', lwd = 3)
rug(unlist(model.frame(m2)['diffVSnew']))
axis(1, cex.axis = 1.5, at = seq(25, 100, 12.5))
axis(2, cex.axis = 1.5)
abline(h = 0, lty = 2, lwd = 0.5)

# Figure F.5
H3 <- intEffect(m3, X = "scale_rank", Z = "diffVSnew", XZ = "diffRanknew", N = 100)
par(mar = c(5, 5, 2, 2))
plot(y = H3[,'beta'], x = H3[,'Zvalues'], 
     ylim = c(-35, 65),
     xlim = c(25, 100),
     type = 'n', 
     xlab = "Electoral Competitiveness", 
     ylab = "Marginal Effect of List Rank",  
     cex = 1.75,
     cex.lab = 1.75,
     axes = FALSE)
polygon(x = c(H3[,'Zvalues'], rev(H3[,'Zvalues'])),
        y = c(H3[,'lb'], rev(H3[,'ub'])),
        col = adjustcolor("grey", alpha.f = 0.95), 
        border = NA)
lines(x = H3[,'Zvalues'], y = H3[,'beta'], lty = 1, col = 'white', lwd = 3)
rug(unlist(model.frame(m3)['diffVSnew']))
axis(1, cex.axis = 1.5, at = seq(25, 100, 12.5))
axis(2, cex.axis = 1.5)
abline(h = 0, lty = 2, lwd = 0.5)

